package io.arukas.endpoint;

import org.keycloak.adapters.OidcKeycloakAccount;
import org.keycloak.adapters.springsecurity.client.KeycloakRestTemplate;
import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * Created by IntelliJ IDEA. <br/>
 * User: 牛玉贤 <br/>
 * Date: 18-8-9 <br/>
 * Time: 下午11:26 <br/>
 * Email: ncc0706@gmail.com <br/>
 * To change this template use File | Settings | File Templates.
 */
@RestController
public class UserEndpoint {

    @Autowired
    private KeycloakRestTemplate keycloakRestTemplate;

    @GetMapping(value = "sendmail")
    public String sendmail() {
        String host = "http://localhost:8082/sendmail";
        return keycloakRestTemplate.getForObject(host, String.class);

    }



    @GetMapping(value = "app/admin")
    @PreAuthorize("hasRole('ADMIN')")   // 需要具有ROLE_ADMIN角色
    public String admin(KeycloakAuthenticationToken token) {
        System.out.println(token.getAccount().getRoles());
        return "hello admin.";
    }


    @GetMapping(value = "app/admin2")
    @PreAuthorize("hasAuthority('ADMIN')") // 需要具有ADMIN权限
    public String admin2(KeycloakAuthenticationToken token) {
        System.out.println(token.getAccount().getRoles());
        return "hello admin2.";
    }

    @GetMapping(value = "app/user")
    @PreAuthorize("hasRole('USER')")
    public String pri(KeycloakAuthenticationToken token) {
        System.out.println(token.getAccount().getRoles());
        return "hello user.";
    }

    @GetMapping(value = "app/sadmin")
    @PreAuthorize("hasRole('SADMIN')")
    public String supAdmin(KeycloakAuthenticationToken token) {
        System.out.println(token.getAccount().getRoles());
        return "hello super admin.";
    }

    @GetMapping("user")
    public String hello(KeycloakAuthenticationToken token) {
        if (ObjectUtils.isEmpty(token)) {
            System.out.println("User not connected.");
            return "not login";
        } else {
            System.out.println("token :" + token);
            OidcKeycloakAccount account = token.getAccount();
            try {
                System.out.println(account.getPrincipal().getName());
                System.out.println(account.getRoles());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "login as " + account.getPrincipal().getName();
        }

    }

}
